package cn.jietuo.juc.c_006_atomicXXX;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/6
 * @description: 比较 AtomicXX 与Synchronized LongAdder的效率
 */
public class T02_AtomicVsSyncVsLongAddr {

    private long count1 = 0;

    synchronized void m1() {
        for (int i = 0; i < 100000; i++) {
            count1++;
        }
    }

    private AtomicLong count2 = new AtomicLong();

    void m2() {
        for (int i = 0; i < 100000; i++) {
            count2.incrementAndGet();
        }
    }

    private LongAdder longAdder = new LongAdder();

    void m3() {
        for (int i = 0; i < 100000; i++) {
            longAdder.increment();
        }
    }

    public static void main(String[] args) throws Exception {
        T02_AtomicVsSyncVsLongAddr t = new T02_AtomicVsSyncVsLongAddr();
        Thread[] threads = new Thread[1000];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> t.m1());
        }
        long startTime = System.currentTimeMillis();
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        System.out.println("sync:count1--" + t.count1 + ",时间：" + (System.currentTimeMillis() - startTime));


        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> t.m2());
        }
        startTime = System.currentTimeMillis();
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println("Atomic:count2--" + t.count2.get() + ",时间：" + (System.currentTimeMillis() - startTime));

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> t.m3());
        }
        startTime = System.currentTimeMillis();
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }

        System.out.println("longAdder:count3--" + t.longAdder.longValue() + ",时间：" + (System.currentTimeMillis() - startTime));
    }
}
